#!/usr/bin/python
#encoding: utf-8;
import subprocess
import sys 
sys.path.append("..")
from s2c.engine.db_helper import DbHelper
from s2c.tools.utils import get_system_date_time
import subprocess
 
class CommandExecutionException(Exception):
    def __init__(self, command: str, exit_code: int) -> None:
        super().__init__(f"command executed fail with exit-code={exit_code}: {command}")

# 实时输出
def cmd_exec(command):
    try:
        p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        #print(type(p))
        # 插入开始数据
        insert_db_str('START', command, 0)
        lines = []
        for line in iter(p.stdout.readline, b''):
            line = line.strip().decode("GB2312")
            print(line)
            insert_db_str(line, command, 1)
            lines.append(line)
        ret_code = p.wait()
        if ret_code:
            #print('-----11111-----cmd_exec failed-----------')
            raise subprocess.CalledProcessError(ret_code, p)
        # 插入结束数据
        #print('-----22222-----cmd_exec failed-----------')
        insert_db_str('END', command, 2)
    except Exception as e:
        #print('----------cmd_exec failed-----------', e)
        insert_db_str(str(e), command, 2)
    return lines


# 更新命令执行的数据
def insert_db_str(line, cmd, status):
    log= {
        'cmd': cmd,
        'str': line.strip(),
        'status': status, # 开始
        'create_time': get_system_date_time()
    }
    log_db = DbHelper()
    start = False
    if status == 0:
        start = True
    #print('-----insert_db_str-----log------', log)
    #print('-----insert_db_str-----start------', start)
    log_db.insert_db_cmd_runing_table(log, start)
    log_db.close()


if __name__ == '__main__':
    cmd_exec("ping baidu.com")
